package com.hlg.yueliao.wxapi;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.sk.weichat.AppConfig;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.WXUploadResult;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.account.BandAndChangePhoneActivity;
import com.sk.weichat.ui.account.DataDownloadActivity;
import com.sk.weichat.ui.account.MultiAccountHelper;
import com.sk.weichat.ui.account.RegisterActivity;
import com.sk.weichat.ui.account.RegisterUserBasicInfoActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.redpacket.PayPasswordVerifyDialog;
import com.sk.weichat.ui.me.redpacket.QuXianActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private static Context mContext;
    private IWXAPI api;
    private int mOldLoginStatus;

    public WXEntryActivity() {
        // 微信登录的回调是到这里，所以可能没有登录，
        noLoginRequired();
    }

    public static void wxLogin(Context ctx) {
        mContext = ctx;
        IWXAPI api = WXAPIFactory.createWXAPI(ctx, Constants.VX_APP_ID, false);
        api.registerApp(Constants.VX_APP_ID);

        if (api != null && api.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "login";
            api.sendReq(req);
        } else{
            ToastUtil.showToast(ctx.getApplicationContext(),"请确认手机是否安装微信客户端");
        }

    }

    public static void wxBand(Context ctx) {
        mContext = ctx;
        IWXAPI api = WXAPIFactory.createWXAPI(ctx, Constants.VX_APP_ID, false);
        api.registerApp(Constants.VX_APP_ID);

        if (api != null && api.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "band";
            api.sendReq(req);
        } else{
            ToastUtil.showToast(ctx.getApplicationContext(),"请确认手机是否安装微信客户端");
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vx_result);

        mOldLoginStatus = MyApplication.getInstance().mUserStatus;
        api = WXAPIFactory.createWXAPI(WXEntryActivity.this, Constants.VX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        SendAuth.Resp mSendAuthResp = ((SendAuth.Resp) resp);
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (Objects.equals(mSendAuthResp.state, "login")) {
                    getOpenId(mSendAuthResp.code);
                } else if (Objects.equals(mSendAuthResp.state, "band")) {
                    bandAccount(mSendAuthResp.code);
                } else {
                    updateCodeToService(mSendAuthResp.code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private void bandAccount(String code) {
        Log.e("xuan", "bandAccount: " + code);

        DialogHelper.showDefaulteMessageProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("loginInfo", code);
        params.put("type", Constants.LOGIN_VX);
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().THIRD_GET_BAND)
                .params(params)
                .build()
                .execute(new BaseCallback<WXUploadResult>(WXUploadResult.class) {

                    @Override
                    public void onResponse(ObjectResult<WXUploadResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(getApplicationContext(), result)) {
                            coreManager.getSelf().setIsWXBand(1);
                            coreManager.getSelf().setWxNikeName(result.getData().getNickname());
                            UserDao.getInstance().updateisWXBand(coreManager.getSelf().getUserId(), 1);
                            UserDao.getInstance().updateWXNikeName(coreManager.getSelf().getUserId(),result.getData().getNickname());
                            ToastUtil.showToast(mContext,"绑定微信成功");
                        }
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }

    private void bandOpenId(String openId) {

        //        int mobilePrefix = PreferenceUtils.getInt(this, Constants.AREA_CODE_KEY, 86);

        User user = coreManager.getSelf();
        DialogHelper.showDefaulteMessageProgressDialog(this);


        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("telephone", user.getTelephone());
        params.put("type", "2");
        params.put("loginInfo", openId);
        params.put("password", user.getPassword());


        HttpUtils.get().url(coreManager.getConfig().USER_THIRD_BIND)
                .params(params)
                .build()
                .execute(new BaseCallback<WXUploadResult>(WXUploadResult.class) {

                    @Override
                    public void onResponse(ObjectResult<WXUploadResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            Toast.makeText(WXEntryActivity.this, "绑定服务器成功", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new EventUpdateBandAccount("result", "ok"));
                            finish();
                        } else {
                            Toast.makeText(WXEntryActivity.this, "绑定服务器失败", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new EventUpdateBandAccount("result", "err"));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }


    private void getOpenId(String code) {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("loginInfo", code);
        params.put("type", Constants.LOGIN_VX);
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        params.put("model", DeviceInfoUtil.getModel());
        params.put("latitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLatitude()));
        params.put("longitude", String.valueOf(MyApplication.getInstance().getBdLocationHelper().getLongitude()));

        HttpUtils.get().url(coreManager.getConfig().THIRD_GET_LOGING)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(getApplicationContext(), result)) {

                            Intent intent;
                            switch (result.getData().getStatus()){

                                case 0: //0,未绑定手机号；
                                    intent = new Intent(WXEntryActivity.this, BandAndChangePhoneActivity.class);
                                    intent.putExtra("loginType", Constants.LOGIN_VX);
                                    intent.putExtra("type", Constants.BAND_PHONE_VX);
                                    intent.putExtra("openId",result.getData().getOpenId());
                                    intent.putExtra("nickname", result.getData().getNickName());
                                    intent.putExtra("sex",  result.getData().getSex());
                                    intent.putExtra("imgurl", result.getData().getHeadImgUrl());
                                    startActivity(intent);
                                    break;

                                case 1://1，成功登录
                                    loginSuccess(result);
                                    break;

                                case 2://2,未完善个人信息；
                                    intent = new Intent(getApplicationContext(), RegisterUserBasicInfoActivity.class);
                                    intent.putExtra(RegisterActivity.EXTRA_AUTH_CODE, result.getData().getAreaCode());
                                    intent.putExtra(RegisterActivity.EXTRA_PHONE_NUMBER, result.getData().getTelephone());
                                    intent.putExtra(RegisterActivity.EXTRA_INVITE_CODE, "");
                                    intent.putExtra(RegisterActivity.EXTRA_PASSWORD, "");
                                    intent.putExtra("nickname", result.getData().getNickName());
                                    intent.putExtra("sex",  result.getData().getSex());
                                    intent.putExtra("imgurl", result.getData().getHeadImgUrl());
                                    intent.putExtra("thirdToken", "");
                                    startActivity(intent);
                                    break;

                                case -1://-1，用户已被禁用；
                                    ToastUtil.showToast(WXEntryActivity.this,"用户已被禁用");
                                    break;
                            }
                        }else{
                            ToastUtil.showToast(WXEntryActivity.this,"登录失败");
                        }
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }

    /**
     * 微信登录成功（已经绑定手机和完善信息）
     * @param result
     */
    private void loginSuccess(ObjectResult<LoginRegisterResult> result) {
        if (result.getData().getIsRegister() == 1) {
            boolean success = false;
            if (result.getResultCode() == com.sk.weichat.volley.Result.CODE_SUCCESS) {
                success = LoginHelper.setLoginUser(mContext, coreManager, "888", result.getData().getPassword(), result);// 设置登录用户信息
            }
            if (success) {
                PreferenceUtils.putBoolean(this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                MultiAccountHelper.onLoginSuccess(mContext, result.getData().getUserId());
                LoginRegisterResult.Settings settings = result.getData().getSettings();
                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                PrivacySettingHelper.setPrivacySettings(WXEntryActivity.this, settings);
                // 登录成功
                LoginRegisterResult.Login login = result.getData().getLogin();
                if (login != null && login.getSerial() != null && login.getSerial().equals(DeviceInfoUtil.getDeviceId(mContext))
                        && mOldLoginStatus != LoginHelper.STATUS_USER_NO_UPDATE && mOldLoginStatus != LoginHelper.STATUS_NO_USER) {
                    // 如果Token没变，上次更新也是完整更新，那么直接进入Main程序
                    // 其他的登录地方都需进入DataDownloadActivity，在DataDownloadActivity里发送此广播
                    LoginHelper.broadcastLogin(WXEntryActivity.this);
                    Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else {
                    // 否则，进入数据下载界面
                    startActivity(new Intent(WXEntryActivity.this, DataDownloadActivity.class));
                }
                finish();
            } else {
                // 登录失败
                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                ToastUtil.showToast(mContext, message);
            }
        }
    }


    private void updateCodeToService(String code) {
        DialogHelper.showDefaulteMessageProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("code", code);

        HttpUtils.get().url(coreManager.getConfig().VX_UPLOAD_CODE)
                .params(params)
                .build()
                .execute(new BaseCallback<WXUploadResult>(WXUploadResult.class) {

                    @Override
                    public void onResponse(ObjectResult<WXUploadResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            WXUploadResult wxUploadResult = result.getData();
                            transfer(wxUploadResult.getOpenid());
                        } else {
                            Toast.makeText(WXEntryActivity.this, "绑定服务器失败", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }

    private void transfer(final String vx_openid) {
        PayPasswordVerifyDialog dialog = new PayPasswordVerifyDialog(this);
        dialog.setAction(getString(R.string.withdraw));
        // amount单位是分，而且是整元乘100得到的分，一定可以被100整除，
        dialog.setMoney(String.valueOf(Integer.valueOf(QuXianActivity.amount) / 100));
        dialog.setOnInputFinishListener(new PayPasswordVerifyDialog.OnInputFinishListener() {
            @Override
            public void onInputFinish(String password) {
                DialogHelper.showDefaulteMessageProgressDialog(WXEntryActivity.this);
                String mAccessToken = coreManager.getSelfStatus().accessToken;
                String mLoginUserId = coreManager.getSelf().getUserId();
                String time = String.valueOf(TimeUtils.sk_time_current_time());

                String str1 = AppConfig.apiKey + vx_openid + mLoginUserId;
                String str2 = Md5Util.toMD5(mAccessToken + QuXianActivity.amount + time);
                String str3 = Md5Util.toMD5(password);
                String secret = Md5Util.toMD5(str1 + str2 + str3);
                Log.d(HttpUtils.TAG, String.format(Locale.CHINA, "addSecret: md5(%s+%s+%s+md5(%s+%s+%s)+md5(%s)) = %s", AppConfig.apiKey, vx_openid, mLoginUserId, mAccessToken, QuXianActivity.amount, time, password, secret));

                final Map<String, String> params = new HashMap<>();
                params.put("access_token", mAccessToken);
                params.put("amount", QuXianActivity.amount);
                params.put("time", time);
                params.put("secret", secret);

                HttpUtils.post().url(coreManager.getConfig().VX_TRANSFER_PAY)
                        .params(params)
                        .build()
                        .execute(new BaseCallback<WXUploadResult>(WXUploadResult.class) {

                            @Override
                            public void onResponse(ObjectResult<WXUploadResult> result) {
                                DialogHelper.dismissProgressDialog();
                                if (result.getResultCode() == 1 && result.getData() != null) {
                                    ToastUtil.showToast(WXEntryActivity.this, R.string.tip_withdraw_success);
                                } else {
                                    ToastUtil.showToast(WXEntryActivity.this, result.getResultMsg());
                                }
                                finish();
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                DialogHelper.dismissProgressDialog();
                                finish();
                                ToastUtil.showErrorData(WXEntryActivity.this);
                            }
                        });
            }
        });
        dialog.setOnDismissListener(dialog1 -> {
            finish();
        });
        dialog.show();
    }
}